package com.zxy.ider.ehome.util;

import java.io.File;
import java.lang.ref.WeakReference;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.SyncStateContract.Constants;
import android.util.Log;
import android.widget.Toast;


import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.zxy.ider.ehome.adapter.DownloadListAdapter;

public class DownloadRequestCallBack extends RequestCallBack<File> {
	private Context context;
	private DownloadManager downloadManager;
	private String did;
	
	public DownloadRequestCallBack(Context context,DownloadManager downloadManager,String did) {
		this.context = context;
		this.downloadManager = downloadManager;
		this.did = did;
	}

	private void refreshListItem() {
		if (userTag == null)
			return;
		WeakReference<DownloadListAdapter.ViewHolder> tag = (WeakReference<DownloadListAdapter.ViewHolder>) userTag;
		DownloadListAdapter.ViewHolder holder = (DownloadListAdapter.ViewHolder) tag.get();
		if (holder != null) {
			holder.refresh();
		}
	}

	@Override
	public void onStart() {
		refreshListItem();
	}

	@Override
	public void onLoading(long total, long current, boolean isUploading) {
		Log.i("hef", current + "/" + total + " = "
				+ (int) (current * 100 / total) + "%");
		refreshListItem();
	}

	@Override
	public void onSuccess(ResponseInfo<File> responseInfo) {
		Log.i("zxy", "onSuccess:responseInfo= "+responseInfo.result.getAbsolutePath());
		refreshListItem();
	}

	@Override
	public void onFailure(HttpException error, String msg) {
		Toast.makeText(context, "下载失败，原因："+msg, Toast.LENGTH_SHORT).show();
		Log.i("zxy", "onFailure: msg="+msg);
		try {
			Toast.makeText(context, "已经从下载对列中移除！", Toast.LENGTH_SHORT).show();
			downloadManager.removeDownload(did);
		} catch (DbException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		refreshListItem();
	}

	@Override
	public void onCancelled() {
		refreshListItem();
	}
}
